<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/8
 * Time: 8:58
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\admin\controller;

use app\admin\model\MessageTemplate;
use app\admin\model\Role;
use app\admin\model\Staff;
use app\merchant\model\PackageOrder;
use app\merchant\model\PackageStyle;
use app\merchant\model\PackageUseLog;
use app\merchant\model\UserPackage;
use app\Request;
use app\merchant\model\Package as PackageModel;

class Package
{
    /**
     * 套餐列表
     */
    public function packageList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }

        $packageWhere[] = ['status', 'in',[1,2]];
        if (isset($param['status'])&&  !empty($param['status']) ){
            $packageWhere[] = ['status', '=', $param['status']];
        }

        if (isset($param['name'])) {
            $packageWhere[] = ['name', 'like', '%' . $param['name'] . '%'];
        }
        $packageModel = new PackageModel();
        $packageList = $packageModel->where($packageWhere)->order('create_time','desc')
                ->limit($start, $limit)->select()->toArray();
        $count = $packageModel->where($packageWhere)->count();
        return adminSuccess('套餐列表', ['list' => $packageList, 'count' => $count]);
    }

    public function packageStyle()
    {
        $packageStyleModel = new PackageStyle();
        $list = $packageStyleModel->where(['status' => 1])->select()->toArray();
        return adminSuccess('套餐卡背景列表', ['list' => $list]);
    }

    public function addPackage(Request $request)
    {
        $param = $request->param();
        $data = [
            'name' => $param['name'],
            'desc' => $param['desc'],
            'style' => $param['style'],
            'style_id' => $param['style_id'],
            'price' => $param['price'],
            'number' => $param['number'],
            'create_time' => time(),
            'status' => 1,
            'remark' => $param['remark'],
            'logo' => $param['logo'],

        ];
        $packageModel = new PackageModel();
        $packageModel->insert($data);
        return adminSuccess('添加成功');

    }

    public function editPackage(Request $request)
    {
        $param = $request->param();
        $data = [
            'name' => $param['name'],
            'desc' => $param['desc'],
            'style' => $param['style'],
            'style_id' => $param['style_id'],
            'price' => $param['price'],
            'number' => $param['number'],
            'create_time' => time(),
            'status' => 1,
            'remark' => $param['remark'],
            'logo' => $param['logo'],
        ];
        $packageModel = new PackageModel();
        $packageModel->where(['id' => $param['id']])->update($data);
        return adminSuccess('修改成功');
    }

    /**
     * 核销套餐卡
     */
    public function usePackage(Request $request)
    {
        $param = $request->param();
        $userPackageModel = new UserPackage();
        $userPackage = $userPackageModel->where(['id' => $param['id']])->find();
        if (empty($userPackage)) {
            return error('核销码有误');
        }
        if ($userPackage['num'] <= 0) {
            return error('此套餐已使用完');
        }
        if ($userPackage['uid'] != $param['uid']) {
            return error('请使用自己的套餐卡');
        }
        if ($userPackage['rand_code'] != $param['rand_code']) {
            return error('核销码已使用请刷新重试');
        }
        $userPackageModel->where(['id' => $param['id']])->dec('num')->update(['rand_code' => createNonceStr(6)]);

        $userPackageLogModel = new PackageUseLog();
        $userPackageLogModel->insert([
            'uid' => $userPackage['uid'],
            'staff_id' => $request->staff_account['id'],
            'package_id' => $userPackage['package_id'],
            'user_package_id' => $userPackage['id'],
            'rand_code' => $userPackage['rand_code'],
            'create_time' => time(),
            'store_id' => $request->staff_account['store_id'],
            'role_id' => $request->staff_account['role_id']
        ]);
        $userModel = new \app\home\model\User();
        if ($userPackage['num'] - 1 == 0){
            $userModel->where(['id' => $userPackage['uid']])->dec('package_num');
        }
        $userInfo  = $userModel->where(['id' => $userPackage['uid']])->find();
        $packageModel = new \app\merchant\model\Package();
        $packageInfo = $packageModel->where(['id'=>$userPackage['package_id']])->find();
        if ( $request->staff_account['store_id']> 0){
            $storeModel = new \app\merchant\model\Store();
            $storeModel->where(['id' => $request->staff_account['store_id']])->inc('package_use_number')->update();
        }
        $messageModel = new MessageTemplate();
        $messageModel->sendMessage($userInfo['openid'], [
            'thing6' => ['value' => $packageInfo['name']],
            'character_string7' => ['value' => 1],
            'character_string10' => ['value' => $userPackage['num'] -1],
            'time8' => ['value' => date('Y-m-d  H:i:s')],

        ], 'package_use'); //


        return adminSuccess('操作成功');
    }

    public function upPackageStatus(Request $request)
    {
        $param = $request->param();
        $packageModel = new PackageModel();
        $packageModel->where(['id' => $param['id']])->update(['status' => $param['status']]);
        return adminSuccess('操作成功');
    }

    /**
     * 套餐卡使用记录
     */
    public function useLog(Request $request)
    {
        $param = $request->param();
        $userPackageModel = new UserPackage();
        $userPackageInfo = $userPackageModel->where(['id' => $param['id']])->find();
        $packageModel = new \app\merchant\model\Package();
        $packageInfo = $packageModel->where(['id' => $userPackageInfo['package_id']])->find();
        $packageUseLogModel = new PackageUseLog();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $list = $packageUseLogModel
            ->where(['user_package_id' => $userPackageInfo['id']])->limit($start, $limit)->select()->toArray();
        $count = $packageUseLogModel->where(['user_package_id' => $userPackageInfo['id']])->count();
        if ($list) {
            $storeId = array_column($list, 'store_id');
            $staffId = array_column($list, 'staff_id');
            $roleId = array_column($list, 'role_id');
            $uid = array_column($list, 'uid');
            $storeModel = new \app\merchant\model\Store();
            $storeListById = [];
            $storeList = $storeModel->where('id', 'in', $storeId)->select()->toArray();
            if ($storeList) {
                $storeListById = array_column($storeList, null, 'id');
            }

            $staffModel = new Staff();
            $staffAccount = $staffModel->where('id', 'in', $staffId)->select()->toArray();
            $staffAccount = array_column($staffAccount, null, 'id');
            $roleModel = new  Role();
            $roleList = $roleModel->where('id', 'in', $roleId)->select()->toArray();
            $roleListByList = array_column($roleList, null, 'id');
            $userModel = new \app\home\model\User();
            $userList = $userModel->where('id', 'in', $uid)->select()->toArray();
            $userListByList = array_column($userList, null, 'id');
            foreach ($list as $key => $value) {
                if (array_key_exists($value['store_id'], $storeListById)) {
                    $list[$key]['store_name'] = $storeListById[$value['store_id']]['name'];
                } else {
                    $list[$key]['store_name'] = '';
                }
                $list[$key]['account_name'] = $staffAccount[$value['staff_id']]['name'];
                $list[$key]['phone'] = $staffAccount[$value['staff_id']]['phone'];
                $list[$key]['role_name'] = $roleListByList[$value['role_id']]['name'];
                $list[$key]['phone'] = $userListByList[$value['uid']]['phone'];
                $list[$key]['avatar'] = $userListByList[$value['uid']]['avatar'];
                $list[$key]['nickname'] = $userListByList[$value['uid']]['nickname'];
                $list[$key]['wachat_nickname'] = $userListByList[$value['uid']]['wachat_nickname'];
                $list[$key]['num'] = $userPackageInfo['num'];
                $list[$key]['total_num'] = $userPackageInfo['total_num'];
                $list[$key]['name'] = $packageInfo['name'];
                $list[$key]['desc'] = $packageInfo['desc'];
            }
        }
        return adminSuccess('套餐卡使用记录', ['list' => $list, 'count' => $count]);
    }

    public function userPackageInfo(Request $request)
    {
        $param = $request->param();
        $userPackageModel = new  UserPackage();
        $myPackageInfo = $userPackageModel->where(['id' => $param['id']])->find();
        if ($myPackageInfo) {
            $packageModel = new  PackageModel();
            $packageInfo = $packageModel->where(['id' => $myPackageInfo['package_id']])->find();
            $myPackageInfo['name'] = $packageInfo['name'];
            $myPackageInfo['desc'] = $packageInfo['desc'];
            $myPackageInfo['price'] = $packageInfo['price'];
            $myPackageInfo['logo'] = $packageInfo['logo'];
            $myPackageInfo['style'] = $packageInfo['style'];
        }
        return adminSuccess('我的套餐详情', $myPackageInfo);
    }

    public function packageBuyLog(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['p.staff_id', '=', $param['staff_id']];
        $where[] = ['p.status', '=', 3];
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['p.update_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['p.update_time', '<=', strtotime($param['end_time'])];
        }

        if (isset($param['pay_type']) && !empty($param['pay_type'])) {
            $where[] = ['p.pay_type', '=', strtotime($param['pay_type'])];
        }
        $PackageOrderModel = new PackageOrder();
        $packageList = $PackageOrderModel
            ->alias('p')
            ->leftJoin('user u', 'u.id = p.uid')
            ->leftJoin('store s', 's.id = p.store_id')
            ->field('p.*,u.phone,u.wachat_nickname,u.nickname,s.name as store_name')
            ->where([
                'p.staff_id' => $request->staff_account['staff_id'],
                'p.status' => 3,
            ])->limit($start, $limit)->select()->toArray();
        $count = $PackageOrderModel
            ->alias('p')
            ->leftJoin('user u', 'u.id = p.uid')
            ->leftJoin('store s', 's.id = p.store_id')
            ->field('p.*,u.phone,u.wachat_nickname,u.nickname,s.name as store_name')
            ->where($where)->count();
        return adminSuccess('员工开卡列表', ['list' => $packageList, 'count' => $count]);
    }
    public function discount(Request $request)
    {
        $param = $request->param();
        $discount = 0;
        $userModel = new \app\home\model\User();
        $userInfo = $userModel->where(['id' => $param['uid']])->find();
        $levelModel = new \app\home\model\Level();
        $levelInfo = $levelModel->where(['id' => $userInfo['level_id']])->find();
        if ($levelInfo['package_preferential'] > 0) { // 针对商城全局的折扣
            $discount  = $levelInfo['package_preferential'];
        } else {
            if ($levelInfo['preferential'] > 0) {  // 全局的折扣
                $discount  = $levelInfo['preferential'];
            }
        }
        return adminSuccess('', ['discount' => $discount]);
    }

    public function  userPackage(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        $userPackageModel = new  UserPackage();
        if (isset($param['type']) && $param['type'] == 1) {
            $where[] = ['up.num', '>', 0];
        }
        if (isset($param['uid']) && $param['uid'] == 1) {
            $where[] = ['up.uid', '=', $param['uid']];
        }
        $orderField['up.id'] = 'desc';
        if (isset($param['price_sort']) && !empty($param['price_sort'])) {
            $orderField['price'] = $param['price_sort'];
            unset($orderField['up.id']);
        }
        if (isset($param['sales_volume_sort']) && !empty($param['sales_volume_sort'])) {
            $orderField['sales_volume'] = $param['sales_volume_sort'];
        }
        if (isset($param['name']) && !empty($param['sales_volume_sort'])) {
            $where[] = ['p.name', 'like', '%' . $param['name'] . '%'];
        }

        $userPackage = $userPackageModel->alias('up')
            ->leftJoin('user u', 'up.uid = u.id')
            ->leftJoin('package p', 'up.package_id = p.id')
            ->field('u.nickname,u.wachat_nickname,u.phone,up.*,p.name,p.desc,p.sales_volume,p.style,p.price,p.logo')
            ->where($where)
            ->limit($start, $limit)->order($orderField)
            ->select()->toArray();

        $count = $userPackageModel->alias('up')
            ->leftJoin('package p', 'up.package_id = p.id')->where($where)
            ->count();

        return adminSuccess('用户套餐卡', ['list' => $userPackage, 'count' => $count]);
    }
    public function packageUseLog(Request $request){
        $packageUseLog = new PackageUseLog();
        if ( $request->staff_account['role_type'] == 3){
            $where[] = ['store_id', '=', $request->staff_account['store_id']];

        }elseif ($request->staff_account['role_type'] == 2){
            $where[] = ['staff_id', '=', $request->staff_account['id']];
        }
        $param = $request->param();
        $userModel =   new \app\home\model\User();
        if (isset($param['account']) &&  !empty($param['account'])){
            $userInfo = $userModel->where('phone|nickname','like','%'.$param['account'].'%')->select()->toArray();
            if ($userInfo){
                $where[] = ['uid','in',array_column($userInfo,'id')];
            }else{
                return adminSuccess('无数据',['list'=>[],'count'=>0]);
            }

        }
        $packageModel = new PackageModel();
        if (isset($param['package_name']) &&  !empty($param['package_name'])){
            $packageInfo = $packageModel->where('name','like','%'.$param['package_name'].'%')->select()->toArray();
            if ($packageInfo){
                $where[] = ['package_id','in',array_column($packageInfo,'id')];
            }else{
                return adminSuccess('无数据',['list'=>[],'count'=>0]);
            }
        }
        $start= 0;
        $limit = 10;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $packageUseLogData = $packageUseLog->where($where)->limit($start,$limit)->select()->toArray();
        $packageUseLogCount = $packageUseLog->where($where)->count();
        if ($packageUseLogData){
            $packageId  = array_column($packageUseLogData,'package_id');
            $userPackageId = array_column($packageUseLogData,'user_package_id');
            $uid = array_column($packageUseLogData,'uid');

            $packageList = $packageModel->where('id','in',$packageId)->select()->toArray();
            $packageListById = array_column($packageList,null,'id');
            $userData  = $userModel->where('id','in',$uid)->select()->toArray();
            $userDataById = array_column($userData,null,'id');
            $userPackageModel = new UserPackage();
            $userPackageData = $userPackageModel->where('id','in',$userPackageId)->select()->toArray();
            $userPackageDataById = array_column($userPackageData,null,'id');
            foreach ($packageUseLogData as $key => $value){
                $packageUseLogData[$key]['package_name'] = $packageListById[$value['package_id']]['name'];
                $packageUseLogData[$key]['desc'] = $packageListById[$value['package_id']]['desc'];
                $packageUseLogData[$key]['price'] = $packageListById[$value['package_id']]['price'];
                $packageUseLogData[$key]['style'] = $packageListById[$value['package_id']]['style'];
                $packageUseLogData[$key]['logo'] = $packageListById[$value['package_id']]['logo'];
                $packageUseLogData[$key]['total_num'] = $userPackageDataById[$value['user_package_id']]['total_num'];
                $packageUseLogData[$key]['num'] = $userPackageDataById[$value['user_package_id']]['num'];
                $packageUseLogData[$key]['user_phone'] = $userDataById[$value['uid']]['phone'];
                $packageUseLogData[$key]['nickname'] = $userDataById[$value['uid']]['nickname'];
                $packageUseLogData[$key]['wachat_nickname'] = $userDataById[$value['uid']]['wachat_nickname'];
            }

        }
        return adminSuccess('核销记录',['list'=>$packageUseLogData,'count'=>$packageUseLogCount]);
    }

}
